//app.js
App({
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs);

    // wx.login调用接口获取登录凭证（code）进而换取用户登录态信息，包括用户的唯一标识（openid） 及本次登录的 会话密钥（session_key）。用户数据的加解密通讯需要依赖会话密钥完成。
    wx.login({
      success: function (login) {
        // 获取用户信息，需要先调用 wx.login 接口。
        wx.getUserInfo({
          // withCredentials是否带上登录态信息
          withCredentials: true,
          success: function (userInfo) {
            console.log(userInfo)
            var requestData = {
              code: login.code, //微信小程序Code,从wx.login回调得到
              iv: userInfo.iv,//iv加密向量从wx.getUserInfo
              encryptedData: userInfo.encryptedData,//encryptedData加密字符从wx.getUserInfo
              // 后面三个参数由服务端提供
              grant_type: 'wechat_openid',
              client_id: 1,
              client_secret: '45uGmBE6qK0CrY4F6WmyflUAXnmeqj5pbbZxVa6n'
            };
            console.log(requestData);
            //发起网络请求向服务器发送requestData
            wx.request({
              url: 'https://wx.duyoucai.com/api/token?date=' + new Date(),
              method: 'POST',
              data: requestData,
              success: function (res) {
                // 从服务器返会的数据setStorageSync缓存access_token、refresh_token、expires_in到本地
                wx.setStorageSync('ak', res.data.access_token);
                wx.setStorageSync('rk', res.data.refresh_token);
                wx.setStorageSync('aktime', res.data.expires_in);
              },
              fail: function (res) {
                console.log(res.errMsg)
              }
            })

          }
        })
      }
    })
  },
  getUserInfo: function (cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        success: function (data) {
          wx.getUserInfo({
            success: function (res) {
              var requestData = {
                encryptedData: res.encryptedData,
                iv: res.iv,
                code: data.code
              };
              that.globalData.userInfo = res;
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },
  globalData: {
    userInfo: null
  }
})